const config = require('../../../config.js');
const bankName = require('../../common/js/bankName.js')
var validate = false
//获取应用实例  
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    multiArray: [],
    multiIndex: 0,
    carts: [],
    showView: true,
    isCover: "",
    coverHeight:"100%",
    vipno:"",
    chooseVipOrBankP: false,
    chooseVipOrBank:false
  },
  /**
   * 选择银行卡
   */
  chooseBank : function(){
    //console.log(this.data.muls);
    this.setData({ muls: this.data.muls, chooseVipOrBank: true, chooseVipOrBankP: false, vipOrBank:'bank'});
  },
  /**
   * 选择一卡通
   */
  chooseVip:function(){
    //console.log(this.data.vipcardmuls);
    this.setData({ vipcardmuls: this.data.vipcardmuls, chooseVipOrBank: true, chooseVipOrBankP: false, vipOrBank: 'vip' });
  },
  /**
   * 银行卡 一卡通 取消
   */
  hideMask:function(){
    this.setData({ chooseVipOrBank: false, chooseVipOrBankP: true, vipOrBank: '' });
  },
  /**
   * 选择银行卡 一卡通
   */
  doChoose:function(e){
    let tempindex = e.currentTarget.dataset.id;
    let tempobj = null;
    if (e.currentTarget.dataset.index == 'bank'){
      tempobj = this.data.muls[tempindex];
      var bankAccount = tempobj.bankAccount;
      var mobile = tempobj.mobile;
      var bankName = tempobj.bankName;
      var bankCardNo = tempobj.bankCardNo;
      var idCard = tempobj.idCard;
      this.setData({
        vipno: "",
        accountNameInputValue: bankAccount,
        mobileInputValue: mobile,
        bankNameInputValue: bankName,
        accountInputValue: bankCardNo,
        idCardInputValue: idCard,
        chooseVipOrBank: false,
        chooseVipOrBankP: true,
        vipOrBank: ''
      })
    }
    if (e.currentTarget.dataset.index == 'vipCard'){
      tempobj = this.data.vipcardmuls[tempindex];
      var vipno = tempobj.vipNo;
      var bankAccount = tempobj.accountName;
      var mobile = tempobj.mobile;
      var bankName = tempobj.bankName;
      var bankCardNo = tempobj.accountNo;
      var idCard = tempobj.idCard;
      if (undefined == idCard || "undefined" == idCard || "null" == idCard || "" == idCard) {
        if (undefined != app.loginUser.idCard && "undefined" != app.loginUser.idCard && "null" != app.loginUser.idCard) {
          idCard = app.loginUser.idCard;
        } else {
          idCard = "";
        }
      }
      this.setData({
        vipno: vipno,
        accountNameInputValue: bankAccount,
        mobileInputValue: mobile,
        bankNameInputValue: bankName,
        accountInputValue: bankCardNo,
        idCardInputValue: idCard,
        chooseVipOrBank: false, 
        chooseVipOrBankP: true, 
        vipOrBank: ''
      })
    }
  },
    chooseimage: function (e) {
      var id = e.target.dataset.id;
      var _this = this;
      let ch = _this.data.carts.length * 100;
      _this.setData({ isCover: "block", coverHeight:ch + "%" });
      wx.chooseImage({
        count: 1, // 默认9  
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
        success: function (res) {
          var dataLength = _this.data.carts.length;
          console.log(dataLength);
          console.log(e.target.dataset.id);
          for (var i = 0; i < dataLength; i++) {
            (function(j){
              if (id == j) {
                console.info(j);
                var param = {};
                var t = j;
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
                wx.uploadFile({
                  url: app.sysInfo.uploadFileUrl,
                  filePath: res.tempFilePaths[0],
                  name: 'file',
                  header: {
                    "Content-Type":
                    "multipart/form-data"
                  },
                  success: function (res) {
                    console.info(res);
                    param['carts[' + t + '].orderPic'] = app.sysInfo.showFileUrl + JSON.parse(res.data).url;
                    _this.setData(param);
                    setTimeout(function () { _this.setData({ "isCover": "none"});},1000);
                  },
                  fail: function (res) {
                    console.log('上传失败');
                  }
                })
              }
            })(i);
          }
        },
        complete:function(){
          setTimeout(function () { _this.setData({ "isCover": "none" }); wx.hideLoading(); }, 1000);
        }
      })
    },


    next: function (e) {//下一步
      var carts = this.data.carts;
      var totalAmount = 0;
      var totalPhotoNum = 0;
      var totalcollectAmount = 0;
      for (var i = 0; i < carts.length; i++) {
        totalAmount = totalAmount + carts[i].deliveryCollection;
        totalcollectAmount = totalcollectAmount + carts[i].collectAmount;
        console.info("下一步");
        console.info(carts[i].orderPic);
        if (carts[i].orderPic != null && carts[i].orderPic != "" && carts[i].orderPic!=undefined) {
          totalPhotoNum = totalPhotoNum + 1;
        } else {
          app.tip("票号:"+carts[i].orderNo+"请添加照片", "none");
          return false;
        }
      }
      this.setData({
        chooseVipOrBankP : true,
        chooseVipOrBank : false,
        showView: false,
        totalAmount: totalAmount.toFixed(2),
        totalcollectAmount: totalcollectAmount.toFixed(2),
        totalNum: carts.length,
        totalPhotoNum: totalPhotoNum
      });
    },


    bindKeyInputAccountName: function (e) {
      this.setData({
        accountNameInputValue: e.detail.value
      })
    },

    bindKeyInputMobile: function (e) {
      this.setData({
        mobileInputValue: e.detail.value
      })
    },

    bindKeyInputBankName: function (e) {
      this.setData({
        bankNameInputValue: e.detail.value
      })
    },

    bindKeyInputBankAccount: function (e) {
      this.setData({
        accountInputValue: e.detail.value
      })
    },

    bindKeyInputIdCard: function (e) {
      this.setData({
        idCardInputValue: e.detail.value
      })
    },

    confirm: function (e) {//提交
      var carts = this.data.carts;
      var accountNameInputValue = this.data.accountNameInputValue;
      var mobileInputValue = this.data.mobileInputValue;
      var bankNameInputValue = this.data.bankNameInputValue;
      var accountInputValue = this.data.accountInputValue;
      var idCardInputValue = this.data.idCardInputValue;
      var vipno = this.data.vipno == undefined ? "" : this.data.vipno;

      if (accountNameInputValue == undefined || accountNameInputValue == null || accountNameInputValue == "") {
        app.tip("请输入开户人", 'none');
        return false;
      }

      //if (mobileInputValue == undefined || mobileInputValue == null || mobileInputValue == "") {
      // app.tip("请输入手机", 'none');
      //  return false;
      //  }

      if (bankNameInputValue == undefined || bankNameInputValue == null || bankNameInputValue == "") {
        app.tip("请输入开户银行", 'none');
        return false;
      }

      if (accountInputValue == undefined || accountInputValue == null || accountInputValue == "") {
        app.tip("请输入卡号", 'none');
        return false;
      }
      console.info("获取设置信息");
      console.info(app.companyInfo.businessSetting);
      if (app.companyInfo.businessSetting.SameAsDefaultDankFlag) {
        if (bankNameInputValue != app.companyInfo.businessSetting.defaultBank) {
          app.tip('请输入' + app.companyInfo.businessSetting.defaultBank + '信息');
          return false;
        }
      } 

      if (idCardInputValue != undefined && idCardInputValue != null && idCardInputValue != "") {
        var regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (!regIdNo.test(idCardInputValue)) {
          app.tip("身份证号填写有误", 'none')
          return false;
        }
      } else {
        app.tip("请输入身份证号", 'none')
        return false;
      }
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      var _Url = config.requestUrl + "withdraw/addWithdraw";
      wx.request({
        url: _Url,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          data: '{' +
          '"vipNo":"' + vipno + '",' +
          '"accountName":"' + accountNameInputValue + '",' +
          '"bankAccount":"' + accountInputValue + '",' +
          '"bankName":"' + bankNameInputValue + '",' +
          '"mobile":"' + app.loginUser.mobile + '",' +
          '"idCard":"' + idCardInputValue + '",' +
          '"order":' + JSON.stringify(carts) + '}'
        },
        success: function (res) {
          console.log("添加取款返回结果");
          console.log(res);
          var msg = "";
          var success = 0;
          if (res.data.code == "100") {
            var content = res.data.content;
            console.info(content);
            if (content != null && content.length > 0) {
              for (var i = 0; i < content.length; i++) {
                if (content[i].remark == "成功") {
                  success = success + 1;
                } else {
                  if (msg == "") {
                    msg = content[i].orderNo + ":" + content[i].remark;
                  } else {
                    msg = msg + "," + content[i].orderNo + ":" + content[i].remark;
                  }
                }
              }
            }
            console.info(success);
            console.info(msg);
            if (success > 0 && msg == "") {
              wx.redirectTo({ url: "../success/success" })
            } else if (success > 0 && msg != "") {
              app.tip("服务端错误", "none");
              wx.redirectTo({ url: "../success/success" })
            } else {
              app.tip("服务端错误", "none");
            }
            wx.hideLoading();
          } else if (res.data.code == "101") {
            wx.hideLoading();
            app.tip(res.data.msg, "none");
          }else{
            wx.hideLoading();
            app.tip(res.data.msg, "none");
          }
        },
        fail: function (res) {
          wx.hideLoading();
          console.log("error res=")
          console.log(res.data)
        }
      });
    },

    queryBankName: function (e) {
      var no = e.detail.value
      if (no) {
        //接口地址没域名，先注释掉
        doQueryBankName(no, this);
      }
    },
    bindMultiPickerChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value);
      console.log(this.data.muls);
      var muls = this.data.muls;
      var bankAccount = muls[e.detail.value].bankAccount;
      var mobile = muls[e.detail.value].mobile;
      var bankName = muls[e.detail.value].bankName;
      var bankCardNo = muls[e.detail.value].bankCardNo;
      var idCard = muls[e.detail.value].idCard;
      this.setData({
        vipno : "",
        accountNameInputValue: bankAccount,
        mobileInputValue: mobile,
        bankNameInputValue: bankName,
        accountInputValue: bankCardNo,
        idCardInputValue: idCard
      })
    },
    bindvipcardMultiPickerChange:function(e){
      console.log('picker发送选择改变，携带值为', e.detail.value);
      console.log(this.data.vipcardmuls);
      var muls = this.data.vipcardmuls;
      var vipno = muls[e.detail.value].vipNo;
      var bankAccount = muls[e.detail.value].accountName;
      var mobile = muls[e.detail.value].mobile;
      var bankName = muls[e.detail.value].bankName;
      var bankCardNo = muls[e.detail.value].accountNo;
      var idCard = muls[e.detail.value].idCard;
      if (undefined == idCard || "undefined" == idCard || "null" == idCard || "" == idCard){
        if (undefined != app.loginUser.idCard && "undefined" != app.loginUser.idCard && "null" != app.loginUser.idCard){
          idCard = app.loginUser.idCard;
        }else{
          idCard = "" ;
        }
      }
      this.setData({
        vipno: vipno,
        accountNameInputValue: bankAccount,
        mobileInputValue: mobile,
        bankNameInputValue: bankName,
        accountInputValue: bankCardNo,
        idCardInputValue: idCard
      })
    },
    imgYu: function (event) {
      var src = event.currentTarget.dataset.current;//获取data-src
      console.info("点击图片");
      console.info(src);
      var imgList = [];
      imgList[0] = src
      //图片预览
      wx.previewImage({
        current: src, // 当前显示图片的http链接
        urls: imgList
      })
    },
    
    onLoad: function (option) {
      console.log('跳转到添加照片页面')
      console.log(option.param);
      var that = this;
      var param = JSON.parse(option.param)
      that.setData({
        carts: param,
        accountNameInputValue: app.loginUser.name
      });
      //获取银行
      var _Url = config.requestUrl + "bankInfo/search";
      wx.request({
        url: _Url,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          vipMemberId: app.loginUser.id
        },
        success: function (res) {
          var content = res.data.content;
          console.log("银行信息");
          var mul = [];
          for (var i = 0; i < content.length; i++) {
            mul[i] = content[i].bankName + " : " + content[i].bankCardNo;
          }
          console.log(mul);
          that.setData({
            multiIndex: 0,
            multiArray: mul,
            muls: content
          })

        },
        fail: function (res) {
          console.log("error res=")
          console.log(res.data)
        }
      });
      //获取一卡通
      wx.request({
        url: config.requestUrl + "order/vipCardInfo",
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
        },
        data: { "code": config.tenantCode, "mobile": app.loginUser.mobile },
        success: function (msg) {
          console.log(msg);
          let content = msg.data.content;
          var vipcardmul = new Array();
          for (var i = 0; i < content.length; i++) {
            vipcardmul[i] = "一卡通: " + content[i].vipNo + " " + content[i].bankName + ": " + content[i].accountNo;
          }
          console.log(vipcardmul);
          that.setData({
            vipcardmultiIndex: 0,
            vipcardmultiArray: vipcardmul,
            vipcardmuls: content
          })
        },
        fail: function (msg) {
        }
      });
    }
})



/**
 * 验证银行卡号并获取银行名称
 */
function doQueryBankName(bankCardNumber, _this) {
  console.info("查询银行名称");
  wx.request({
    url: app.sysInfo.getBankNameUrl + bankCardNumber,
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success: (res) => {
      console.log(res)
      var data = res.data;
			/*
			bank: "HRBANK", validated: true, cardType: "DC", key: "6217524514000042458", messages[],stat:"ok"
			*/
      var isFail = false
      var failMsg = ''
      if (data && data.bank) {
        var name = bankName.getName(data.bank)
        if (name) {
          _this.setData({ bankNameInputValue: name })
          validate = data.validated
        } else {
          isFail = true
          failMsg = '获取银行名称失败'
        }
      } else {
        if (data.messages && data.messages.length > 0) {
          failMsg = data.messages[0].errorCodes
        } else {
          failMsg = res.errMsg
        }
      }
      if (isFail) {
        if (failMsg) {
          app.tip(failMsg, 'loading')
        }
        _this.setData({ bankNameInputValue: "" })
        validate = false
      }
    },
    fail: function ({ errMsg }) {
      validate = false
      _this.setData({ bankNameInputValue: "" })
      app.tip(errMsg, 'loading')
    }
  })
}